# car.py - By: YANCL - 周三 7月 19 2023

from pyb import Pin, Timer  #导入引脚和定时器

import time, pyb

red   = pyb.LED(1)
green = pyb.LED(2)
blue  = pyb.LED(3)

inverse_left=False  #change it to True to inverse left wheel
inverse_right=False #change it to True to inverse right wheel

ain1 =  Pin('P0', Pin.OUT_PP)   #OUT_PP 是设置上拉电阻
ain2 =  Pin('P1', Pin.OUT_PP)
bin1 =  Pin('P2', Pin.OUT_PP)
bin2 =  Pin('P3', Pin.OUT_PP)   #新建4个引脚，控制电机方向
ain1.low()                      #引脚初始化，都为低电平
ain2.low()
bin1.low()
bin2.low()

pwma = Pin('P7')                #定义P7为PWMA
pwmb = Pin('P8')                #定义P8为PWMB
tim = Timer(4, freq=1000)       #设置定时器4，频率1000Hz
ch1 = tim.channel(1, Timer.PWM, pin=pwma)   #定时器4通道1，对用P7
ch2 = tim.channel(2, Timer.PWM, pin=pwmb)   #定时器4通道2，对应P8
ch1.pulse_width_percent(0)      #初始化，设置通道占空比为0
ch2.pulse_width_percent(0)      #初始化，设置通道占空比为0

#定义一个run函数，形参（左电机速度left_speed，右电机速度right_speed）
def run(left_speed, right_speed):
    #下面四行是设置电机的正反转,这里可以先测试电机的正反转，然后如果有问题，交换线序
    if inverse_left==True:
        left_speed=(-left_speed)
    if inverse_right==True:
        right_speed=(-right_speed)

    #设置电机正反转，输出两路PWM信号
    if left_speed < 0:
        ain1.low()
        ain2.high()
        red.off()   #左电机反转，红灯关闭
    else:
        ain1.high()
        ain2.low()
        red.on()    #左电机正转，红灯开启
    ch1.pulse_width_percent(int(abs(left_speed)))

    if right_speed < 0:
        bin1.low()
        bin2.high()
        blue.off()
    else:
        bin1.high()
        bin2.low()
        blue.on()
    ch2.pulse_width_percent(int(abs(right_speed)))
#将这个文件保存为car.py
